package com.example.gokchinesefoodmappcdev.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.example.gokchinesefoodmappcdev.util.ResultData;
import com.example.gokchinesefoodmappcdev.util.TimeCacheUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@Slf4j
public class LoginController {





    /*
    校验token
    * */

    @ResponseBody
    @RequestMapping("/rest/authStatus")
    public void authStatus(HttpServletResponse response){
        // 4. 响应结果
        ResultData resultData = new ResultData(ResultData.VERIFY_SUCCESS, "验证成功");
        try{
            response.getWriter().println(new ObjectMapper().writeValueAsString(resultData));
        } catch (IOException e) {
            log.error(e.getMessage());
        }

    }

    @RequestMapping("/toLoginPage")
    public String toLoginPage(){
        return "login";
    }

    @RequestMapping("/order")
    public String order(){
        return "login";
    }
    /*
     * 获取验证码，返回的时验证的路径
     * */
    @ResponseBody
    @RequestMapping("/user/getValidateCode")
    public Map<String,String> getValidateCode(HttpServletRequest request, HttpSession session){
        String path = LoginController.class.getClassLoader().getResource("static").getPath();

        File file = new File(path + "/temp/validateCode");
        if(!file.exists()){
            file.mkdirs();
        }

        //生成验证码的图片名
        String validateName = UUID.randomUUID() + ".jpg";
        //生成图片的输出地址
        StringBuilder validatePathName = new StringBuilder(path+"/temp/validateCode/"+validateName);


        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 100, 4, 4);
        //ShearCaptcha captcha = new ShearCaptcha(200, 100, 4, 4);

        //图形验证码写出，可以写出到文件，也可以写出到流
        captcha.write(validatePathName.toString());

        //获取code
        String code = captcha.getCode();
        //获取code唯一标识
        String codeId = UUID.randomUUID().toString();

        //创建缓存，设置1分钟过期
        //验证码值存入缓存
        TimeCacheUtil.put(codeId,code,360000);

        //将验证码地址响应给前端
        HashMap<String, String> resultMap = new HashMap<>();
        resultMap.put("code","200");
        resultMap.put("imageUrl", "/temp/validateCode/"+validateName);
        resultMap.put("ImageCode",code);
        resultMap.put("codeId",codeId);

        return resultMap;
    }
}
